import sys
import os.path

def add_protect(dsp_filename):
	with open(dsp_filename, 'rb') as dsp1_rom:
		dsp1_bytes = bytearray(dsp1_rom.read())
		#print len(dsp1_bytes)
	
	i = 0
	j = 0
	rom_len = len(dsp1_bytes)
	prg_len = 3 * rom_len / 4
	data_len = rom_len / 4
	dsp_prg_protect = bytearray()
	dsp_dat_protect = bytearray()
	while i < prg_len:
		dsp_prg_protect[j:j+4] = dsp1_bytes[i:i+3] + bytearray.fromhex(u'ff')
		i += 3
		j += 4
	
	j = 0	
	while i < rom_len:
		dsp_dat_protect[j:j+2] = dsp1_bytes[i:i+2]
		i += 2
		j += 2
	
	with open(os.path.splitext(dsp_filename)[0] + '_prg.bin', 'wb') as dsp1_prg:
		dsp1_prg.write(dsp_prg_protect)
	
	with open(os.path.splitext(dsp_filename)[0] + '_dat.bin', 'wb') as dsp1_dat:
		dsp1_dat.write(dsp_dat_protect)

if __name__ == '__main__':
	if len(sys.argv) < 2:
		print 'Syntax: add_protect.py [dsp_rom]'
		print 'Only bigendian supported at the moment (dsp*.bin)'
	else:
		add_protect(sys.argv[1])
